package org.jeecg.common.system.base.entity;

import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import lombok.Getter;
import org.springframework.util.Assert;

import java.io.Serializable;

/**
 * 字段 Function 与 RedisKey 前缀载体
 *
 * @author chechen
 * @date 2022-04-16
 */
@Getter
public class FieldRedisItem<E> implements Serializable {
    private static final long serialVersionUID = 1L;

    /**
     * 字段 function
     */
    private final SFunction<E, Serializable> fieldFunction;

    /**
     * redisKey 前缀
     */
    private final String keyPrefix;

    /**
     * 是否为主键
     */
    private final boolean primaryKey;

    /**
     * 是否为普通字段
     */
    public boolean isField() {
        return !this.primaryKey;
    }

    /**
     * 检测function是否为空，为空表示要全查
     */
    public boolean isSelectAllData() {
        return fieldFunction == null;
    }

    /**
     * 全参构造函数
     */
    public FieldRedisItem(SFunction<E, Serializable> fieldFunction, String keyPrefix, boolean primaryKey) {
        this.fieldFunction = fieldFunction;
        this.keyPrefix = keyPrefix;
        this.primaryKey = primaryKey;
    }

    /**
     * 全参构建
     */
    public static <E> FieldRedisItem<E> build(SFunction<E, Serializable> fieldFunction, String keyPrefix, Boolean primaryKey) {
        checkFieldFunction(fieldFunction);
        checkKeyPrefix(keyPrefix);
        checkPrimaryKey(primaryKey);

        return new FieldRedisItem<>(fieldFunction, keyPrefix, primaryKey);
    }

    /**
     * 构建普通字段
     */
    public static <E> FieldRedisItem<E> build(SFunction<E, Serializable> fieldFunction, String keyPrefix) {
        checkFieldFunction(fieldFunction);
        checkKeyPrefix(keyPrefix);

        return new FieldRedisItem<>(fieldFunction, keyPrefix, false);
    }


    /**
     * 构建普通字段
     */
    public static <E> FieldRedisItem<E> build(String keyPrefix) {
        checkKeyPrefix(keyPrefix);

        return new FieldRedisItem<>(null, keyPrefix, false);
    }


    private static <E> void checkFieldFunction(SFunction<E, Serializable> fieldFunction) {
        Assert.notNull(fieldFunction, "FieldFunction must not be null!");
    }

    private static void checkKeyPrefix(String keyPrefix) {
        Assert.notNull(keyPrefix, "KeyPrefix must not be null!");
    }

    private static void checkPrimaryKey(Boolean primaryKey) {
        Assert.notNull(primaryKey, "PrimaryKey must not be null!");

    }

}
